package org.skipper.samples.thread.communication;

/**
 * Created with IntelliJ IDEA.
 * Description: 线程间通信：synchronized、wait、notifyAll
 *
 * @author shoujian
 * Date: 2022-06-27
 * Time: 10:54
 */
public class Communication1 {

    public static void main(String[] args) {

        final Object obj1 = new Object();
        final Object obj2 = new Object();
        final Object obj3 = new Object();

        TestThread thread1 = new TestThread(obj1, obj2);
        TestThread thread2 = new TestThread(obj2, obj3);
        TestThread thread3 = new TestThread(obj3, obj1);

        thread1.setName("线程1");
        thread1.start();

        try {
            Thread.sleep(500L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        thread2.setName("线程2");
        thread2.start();

        try {
            Thread.sleep(500L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        thread3.setName("线程3");
        thread3.start();
    }


    static class TestThread extends Thread {

        private Object obj1 = null;

        private Object obj2 = null;

        public TestThread(Object obj1, Object obj2) {
            this.obj1 = obj1;
            this.obj2 = obj2;
        }

        @Override
        public void run() {

            synchronized (obj1) {
                System.out.println(Thread.currentThread().getName() + "准备进入下一个");

                synchronized (obj2) {
                    for (int i = 0; i < 10; i++) {
                        System.out.println(Thread.currentThread().getName() + "_" + i);
                    }
                    obj2.notifyAll();
                }
                obj1.notifyAll();
                System.out.println(Thread.currentThread().getName()+"_end");
            }


        }

    }


}
